package org.hscoder.websearcher.repository;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortMode;
import org.elasticsearch.search.sort.SortOrder;
import org.hscoder.websearcher.domain.EsFilm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.util.StringUtils;

public class EsFilmRepositoryImpl implements EsFilmRepositoryCustom {

    @Autowired
    private ElasticsearchTemplate template;

    @Override
    public Page<EsFilm> interSearch(String period, String sort, String region, String language, Pageable pageable) {

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        if (!StringUtils.isEmpty(period)) {
            boolQueryBuilder.must(QueryBuilders.termQuery("period", period));
        }

        if (!StringUtils.isEmpty(sort)) {
            boolQueryBuilder.must(QueryBuilders.termQuery("sorts", sort));
        }
        if (!StringUtils.isEmpty(region)) {
            boolQueryBuilder.must(QueryBuilders.termQuery("regions", region));
        }

        if (!StringUtils.isEmpty(language)) {
            boolQueryBuilder.must(QueryBuilders.termQuery("language", language));
        }

        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQueryBuilder).withSort(SortBuilders.fieldSort("score").order(SortOrder.DESC)).withPageable(pageable).build();
        return template.queryForPage(searchQuery, EsFilm.class);
    }
}
